<template>
  <div>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="一级分类">
        <el-select v-model="from.category1Id" :disabled="show" placeholder="请选择" @change="select(1)">
          <el-option v-for="item in list1" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select v-model="from.category2Id" :disabled="show" placeholder="请选择" @change="select(2)">
          <el-option v-for="item in list2" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select v-model="from.category3Id" :disabled="show" placeholder="请选择" @change="select(3)">
          <el-option v-for="item in list3" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 将三级联动封装成一个全局组件
export default {
  name: 'CategorySelect',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list1: [],
      list2: [],
      list3: [],
      // 收集分类的ID
      from: {
        category1Id: '',
        category2Id: '',
        category3Id: ''
      }
    }
  },
  mounted() {
    this.category1()
  },
  methods: {
    // 获取一级分类
    async category1() {
      const res = await this.$api.attr.category1()
      if (res.code === 200) {
        this.list1 = res.data
      }
    },
    async select(e) {
      if (e === 1) {
        this.from.category2Id = ''
        this.from.category3Id = ''
        this.list2 = []
        this.list3 = []
        const res = await this.$api.attr.category2(this.from.category1Id)
        if (res.code === 200) {
          this.list2 = res.data
        }
        this.$emit('select', { categoryId: this.from.category1Id, level: e })
      } else if (e === 2) {
        this.list3 = []
        this.from.category3Id = ''
        const res = await this.$api.attr.category3(this.from.category2Id)
        if (res.code === 200) {
          this.list3 = res.data
        }
        this.$emit('select', { categoryId: this.from.category2Id, level: e })
      } else {
        this.$emit('select', { categoryId: this.from.category3Id, level: e })
      }
    }
  }
}
</script>

<style lang="sass" scoped>

</style>
